#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "barchartwidget.h"
#include "piechartwidget.h"
#include "linechartwidget.h"
#include <QRandomGenerator>
#include <QDateTime>
#include <QMessageBox>
#include <QTreeWidgetItem>
#include <QIcon>
#include <QDesktopServices>
#include <QUrl>
#include <QProgressDialog>
#include <QRegularExpression>
#include <QVBoxLayout>
#include <QTimer>
#include <QDebug>
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    std::cout << "=== MAINWINDOW CONSTRUCTOR START ===" << std::endl;
    
    try {
        qDebug() << "MainWindow constructor started";
        std::cout << "MainWindow constructor started" << std::endl;
        
        std::cout << "Creating Ui::MainWindow..." << std::endl;
        if (!ui) {
            std::cout << "CRITICAL ERROR: Failed to create Ui::MainWindow!" << std::endl;
            throw std::runtime_error("Failed to create Ui::MainWindow");
        }
        std::cout << "Ui::MainWindow created successfully" << std::endl;
        
        qDebug() << "Setting up UI...";
        std::cout << "Calling ui->setupUi(this)..." << std::endl;
        ui->setupUi(this);
        std::cout << "ui->setupUi(this) completed successfully" << std::endl;
        qDebug() << "UI setup completed";
        
        // 验证关键UI元素是否存在
        std::cout << "Verifying critical UI elements..." << std::endl;
        
        if (!ui->stackedWidget) {
            std::cout << "CRITICAL ERROR: stackedWidget is null!" << std::endl;
            qDebug() << "CRITICAL ERROR: stackedWidget is null!";
            throw std::runtime_error("stackedWidget is null");
        }
        std::cout << "stackedWidget verified" << std::endl;
        
        if (!ui->account_edit) {
            std::cout << "CRITICAL ERROR: account_edit is null!" << std::endl;
            qDebug() << "CRITICAL ERROR: account_edit is null!";
            throw std::runtime_error("account_edit is null");
        }
        std::cout << "account_edit verified" << std::endl;
        
        if (!ui->password_edit) {
            std::cout << "CRITICAL ERROR: password_edit is null!" << std::endl;
            qDebug() << "CRITICAL ERROR: password_edit is null!";
            throw std::runtime_error("password_edit is null");
        }
        std::cout << "password_edit verified" << std::endl;
        
        if (!ui->login_button) {
            std::cout << "CRITICAL ERROR: login_button is null!" << std::endl;
            qDebug() << "CRITICAL ERROR: login_button is null!";
            throw std::runtime_error("login_button is null");
        }
        std::cout << "login_button verified" << std::endl;
        
        qDebug() << "All critical UI elements verified";
        std::cout << "All critical UI elements verified successfully" << std::endl;
        
        qDebug() << "Setting StackedWidget index...";
        ui->stackedWidget->setCurrentIndex(0);  // 默认显示登录页面
        qDebug() << "StackedWidget index set";
        
        qDebug() << "Setting default login values and focus...";
        // 设置默认的用户名和密码
        ui->account_edit->setText("admin");
        ui->account_edit->setFocus();
        qDebug() << "Default username set and focus applied to account_edit";
        
        ui->password_edit->setText("1");
        qDebug() << "Default password set to password_edit";
        
        // 设置版本号
        ui->version_label->setText("版本: v1.2");
        qDebug() << "Version label set to v1.2";
        
        qDebug() << "Connecting button signals...";
        // 注意：login_button的clicked信号会通过Qt的自动连接机制自动连接到on_login_button_clicked槽
        // 所以这里不需要手动连接login_button，否则会导致双重触发
        // connect(ui->login_button, &QPushButton::clicked, this, &MainWindow::on_login_button_clicked);
        qDebug() << "Login button uses auto-connection (on_login_button_clicked)";
        
        // 连接退出按钮的点击事件
        connect(ui->exit_button, &QPushButton::clicked, this, &MainWindow::on_exit_button_clicked);
        qDebug() << "Exit button connected";
        
        // 连接退出按钮1的点击事件
        connect(ui->exit_button1, &QPushButton::clicked, this, &MainWindow::on_exit_button1_clicked);
        qDebug() << "Exit button1 connected";
        
        // 初始化右键菜单
        contextMenu = new QMenu(this);
        sendEmailAction = new QAction("发送邮件", this);
        contextMenu->addAction(sendEmailAction);
        qDebug() << "Context menu initialized";
    
        // 设置右键菜单样式，修复悬停时文字变白的问题
        contextMenu->setStyleSheet(
            "QMenu {"
            "    background-color: #f0f0f0;"
            "    border: 1px solid #ccc;"
            "    border-radius: 4px;"
            "    padding: 2px;"
            "}"
            "QMenu::item {"
            "    background-color: transparent;"
            "    color: #333;"
            "    padding: 6px 20px;"
            "    border-radius: 2px;"
            "}"
            "QMenu::item:selected {"
            "    background-color: #0078d4;"
            "    color: white;"
            "}"
            "QMenu::item:hover {"
            "    background-color: #e5f3ff;"
            "    color: #333;"
            "}"
        );
        
        // 连接信号和槽
        connect(sendEmailAction, &QAction::triggered, this, &MainWindow::sendEmailForAlarm);
        
        // 初始化Tab右键菜单
        tabContextMenu = new QMenu(this);
        openInNewWindowAction = new QAction("在新窗口中打开", this);
        tabContextMenu->addAction(openInNewWindowAction);
        
        // 设置Tab右键菜单样式
        tabContextMenu->setStyleSheet(
            "QMenu {"
            "    background-color: #f0f0f0;"
            "    border: 1px solid #ccc;"
            "    border-radius: 4px;"
            "    padding: 2px;"
            "}"
            "QMenu::item {"
            "    background-color: transparent;"
            "    color: #333;"
            "    padding: 6px 20px;"
            "    border-radius: 2px;"
            "}"
            "QMenu::item:selected {"
            "    background-color: #0078d4;"
            "    color: white;"
            "}"
            "QMenu::item:hover {"
            "    background-color: #e5f3ff;"
            "    color: #333;"
            "}"
        );
        
        // 连接Tab右键菜单信号和槽
        connect(openInNewWindowAction, &QAction::triggered, this, &MainWindow::openTabInNewWindow);
        
        qDebug() << "Starting initialization functions...";
        std::cout << "Starting initialization functions..." << std::endl;
        
        std::cout << "Calling initWidget()..." << std::endl;
        initWidget();
        qDebug() << "initWidget completed";
        std::cout << "initWidget completed successfully" << std::endl;
        
        std::cout << "Calling initActiveTable()..." << std::endl;
        initActiveTable();
        qDebug() << "initActiveTable completed";
        std::cout << "initActiveTable completed successfully" << std::endl;
        
        std::cout << "Calling initVoiceTable()..." << std::endl;
        initVoiceTable();
        qDebug() << "initVoiceTable completed";
        std::cout << "initVoiceTable completed successfully" << std::endl;
        
        std::cout << "Calling initAcknowledgedTable()..." << std::endl;
        initAcknowledgedTable();
        qDebug() << "initAcknowledgedTable completed";
        std::cout << "initAcknowledgedTable completed successfully" << std::endl;
        
        std::cout << "Calling addMultipleNodes()..." << std::endl;
        addMultipleNodes();
        qDebug() << "addMultipleNodes completed";
        std::cout << "addMultipleNodes completed successfully" << std::endl;
        
        std::cout << "Calling initColorBlockFlashing()..." << std::endl;
        initColorBlockFlashing();
        qDebug() << "initColorBlockFlashing completed";
        std::cout << "initColorBlockFlashing completed successfully" << std::endl;
        
        // 为TabWidget设置右键菜单
        std::cout << "Setting up TabWidget context menu..." << std::endl;
        if (ui->tabWidget && ui->tabWidget->tabBar()) {
            ui->tabWidget->tabBar()->setContextMenuPolicy(Qt::CustomContextMenu);
            connect(ui->tabWidget->tabBar(), &QTabBar::customContextMenuRequested, this, &MainWindow::showTabContextMenu);
        }
        std::cout << "TabWidget context menu setup completed" << std::endl;
        
        qDebug() << "MainWindow constructor finished successfully";
        std::cout << "MainWindow constructor finished successfully" << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Exception in MainWindow constructor: " << e.what() << std::endl;
        qDebug() << "Exception in MainWindow constructor:" << e.what();
        throw;
    } catch (...) {
        std::cout << "Unknown exception in MainWindow constructor" << std::endl;
        qDebug() << "Unknown exception in MainWindow constructor";
        throw;
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initWidget()
{

    BarChartWidget *barChart = new BarChartWidget();

    // 设置自定义报警等级名称
    QVector<QString> levelNames = {
        "紧急", "严重", "高危", "高级", "中级",
        "一般", "低级", "提示", "信息", "调试"
    };
    barChart->setAlarmLevelNames(levelNames);

    // 设置标题
    barChart->setTitle("报警等级分布统计");

    // 设置示例数据
    QVector<int> alarmData = {1, 1, 5, 2, 6, 7, 10, 7, 3, 1};
    barChart->setAlarmData(alarmData);
    ui->bar_layout->addWidget(barChart);


    PieChartWidget *pieChart = new PieChartWidget();
    pieChart->setTitle("报警统计");
    pieChart->setLabels("TMSR", "TMSRState", "TMSRCommand", "TMSRTalk");
    pieChart->setData(120.5, 85.3, 67.8, 45.2);
    pieChart->setShowPercentage(true);
    pieChart->setHighlightEnabled(true);
    ui->pie_layout->addWidget(pieChart);


    DailyAlarmChart *alarmChart = new DailyAlarmChart();
    alarmChart->setChartTitle("最近30天报警统计");
    alarmChart->setAxisTitles("日期", "报警次数");
    alarmChart->setChartColors(Qt::darkRed, Qt::red);

    // 生成示例数据
    QDateTime currentDate = QDateTime::currentDateTime();
    for (int i = 0; i < 30; ++i) {
        QDateTime date = currentDate.addDays(-29 + i);
        int alarmCount = QRandomGenerator::global()->bounded(0, 20);
        alarmChart->addAlarmData(date, alarmCount);
    }

    // 更新图表
    alarmChart->updateChart();
    ui->line_layout->addWidget(alarmChart);

}
void MainWindow::initVoiceTable(){
    QTableWidget *voiceTable = ui->voice_alarm_table;

    // 设置表格行数
    voiceTable->setRowCount(10);

    // 设置表格数据
    QStringList alarmTime = {"2024-01-15 08:30:15", "2024-01-15 09:45:22", "2024-01-15 10:12:08", "2024-01-15 11:33:45", "2024-01-15 12:55:30", "2024-01-15 14:20:18", "2024-01-15 15:42:55", "2024-01-15 16:18:33", "2024-01-15 17:05:12", "2024-01-15 18:27:40"};
    QStringList alarmServerity = {"紧急", "严重", "高危", "高级", "中级", "一般", "低级", "提示", "信息", "调试"};
    QStringList description = {"加速器真空系统压力异常", "束流位置偏移超限", "磁铁电源故障", "RF系统功率下降", "冷却水温度过高", "束流强度不稳定", "真空泵运行异常", "电源电压波动", "数据采集系统通信中断", "设备状态监控异常"};

    for (int row = 0; row < 10; ++row)
    {
        QTableWidgetItem *item = nullptr;

        // 报警时间
        item = new QTableWidgetItem(alarmTime[row]);
        voiceTable->setItem(row, 0, item);

        // 报警严重性
        item = new QTableWidgetItem(alarmServerity[row]);
        voiceTable->setItem(row, 1, item);

        // 描述
        item = new QTableWidgetItem(description[row]);
        voiceTable->setItem(row, 2, item);
    }

    // 设置表格属性
    voiceTable->setAlternatingRowColors(true);
    voiceTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    voiceTable->setSelectionMode(QAbstractItemView::SingleSelection);
    voiceTable->horizontalHeader()->setStretchLastSection(true);
    voiceTable->verticalHeader()->setVisible(false);
    voiceTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    voiceTable->setSortingEnabled(true);
}

void MainWindow::initAcknowledgedTable(){
    QTableWidget *acknowledgedTable = ui->acknowledged_alarm_table;
    acknowledgedTable->setRowCount(0);
}

void MainWindow::initActiveTable()
{
    QTableWidget *activeTable = ui->active_alarm_table;

    // 设置表格行数
    activeTable->setRowCount(10);

    // 设置表格数据
    QStringList pv = {"TMSR:Vacuum:Pressure", "TMSR:Beam:Position:X", "TMSR:Magnet:PS01:Current", "TMSR:RF:Power:Forward", "TMSR:Cooling:Water:Temp", "TMSR:Beam:Current", "TMSR:Vacuum:Pump01:Status", "TMSR:Power:Supply:Voltage", "TMSR:DAQ:Communication", "TMSR:Monitor:System:Status"};
    QStringList description = {"加速器真空系统压力", "束流水平位置", "磁铁电源01电流", "RF前向功率", "冷却水温度", "束流强度", "真空泵01状态", "电源电压", "数据采集通信", "监控系统状态"};
    QStringList alarmServerity = {"紧急", "严重", "高危", "高级", "中级", "一般", "低级", "提示", "信息", "调试"};
    QStringList alarmMessage = {"压力超出安全范围", "位置偏移过大", "电流异常", "功率下降", "温度过高", "强度不稳定", "泵运行异常", "电压波动", "通信中断", "状态异常"};
    QStringList alarmTime = {"2024-01-15 08:30:15", "2024-01-15 09:45:22", "2024-01-15 10:12:08", "2024-01-15 11:33:45", "2024-01-15 12:55:30", "2024-01-15 14:20:18", "2024-01-15 15:42:55", "2024-01-15 16:18:33", "2024-01-15 17:05:12", "2024-01-15 18:27:40"};
    QStringList alarmValue = {"1.2e-6 Torr", "2.5 mm", "98.5 A", "45.2 kW", "85.3 °C", "120.5 mA", "故障", "220.5 V", "超时", "离线"};
    QStringList pvSeverity = {"MAJOR", "MINOR", "MAJOR", "MINOR", "MAJOR", "MINOR", "MAJOR", "MINOR", "MAJOR", "MINOR"};
    QStringList pvMessage = {"真空度异常", "束流偏移", "电流故障", "功率异常", "温度报警", "强度波动", "设备故障", "电压异常", "网络故障", "系统异常"};

    for (int row = 0; row < 10; ++row)
    {
        QTableWidgetItem *item = nullptr;

        // PV名称
        item = new QTableWidgetItem();
        item->setData(Qt::DisplayRole, pv[row]);
        item->setIcon(QIcon(":/icons/pv.png"));
        activeTable->setItem(row, 0, item);

        // 描述
        item = new QTableWidgetItem(description[row]);
        activeTable->setItem(row, 1, item);

        // PV值
        item = new QTableWidgetItem(pv[row]);
        activeTable->setItem(row, 2, item);

        // 描述
        item = new QTableWidgetItem(description[row]);
        activeTable->setItem(row, 3, item);

        // 报警严重性
        item = new QTableWidgetItem(alarmServerity[row]);
        activeTable->setItem(row, 4, item);

        // 报警消息
        item = new QTableWidgetItem(alarmMessage[row]);
        activeTable->setItem(row, 5, item);

        // 报警时间
        item = new QTableWidgetItem(alarmTime[row]);
        activeTable->setItem(row, 6, item);

        // 报警值
        item = new QTableWidgetItem(alarmValue[row]);
        activeTable->setItem(row, 7, item);

        // PV严重性
        item = new QTableWidgetItem(pvSeverity[row]);
        activeTable->setItem(row, 8, item);

        // PV消息
        item = new QTableWidgetItem(pvMessage[row]);
        activeTable->setItem(row, 9, item);
    }

    // 设置表格属性
    activeTable->setAlternatingRowColors(true);
    activeTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    activeTable->setSelectionMode(QAbstractItemView::SingleSelection);
    activeTable->horizontalHeader()->setStretchLastSection(true);
    activeTable->verticalHeader()->setVisible(false);
    activeTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    activeTable->setSortingEnabled(true);

    // 设置右键菜单
    activeTable->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(activeTable, &QTableWidget::customContextMenuRequested, this, &MainWindow::showContextMenu);
}

void MainWindow::on_login_button_clicked()
{
    qDebug() << "=== NEW LOGIN FUNCTION START ===";
    
    // 获取并验证输入
    QString account = ui->account_edit->text().trimmed();
    QString password = ui->password_edit->text().trimmed();
    
    qDebug() << "Login attempt - Account:" << account << "Password:" << password;
    
    // 检查输入是否为空
    if (account.isEmpty() || password.isEmpty()) {
        qDebug() << "Empty credentials provided";
        QMessageBox::warning(this, "登录失败", "请输入账号和密码！");
        return;
    }
    
    // 验证凭据
    if (account == "admin" && password == "1") {
        qDebug() << "Login successful - switching to main interface";
        
        // 清空输入框
        ui->account_edit->clear();
        ui->password_edit->clear();
        
        // 设置用户标签
        ui->label_25->setText(account);
        
        // 切换到主界面
        ui->stackedWidget->setCurrentIndex(1);
        
        qDebug() << "Interface switched to main page";
    } else {
        qDebug() << "Login failed - invalid credentials";
        QMessageBox::warning(this, "登录失败", "账号或密码错误！");
    }
    
    qDebug() << "=== NEW LOGIN FUNCTION END ===";
}

void MainWindow::on_exit_button_clicked(){
    this->close();
}

void MainWindow::on_exit_button1_clicked(){
    this->close();
}

void MainWindow::addMultipleNodes()
{
    QTreeWidget *treeWidget = ui->alarm_tree;
    QStyle *style = treeWidget->style();
    QTreeWidgetItem *root1 = new QTreeWidgetItem(treeWidget);
    root1->setText(0, "TMSR");
    root1->setIcon(0, style->standardIcon(QStyle::SP_ComputerIcon));

    QTreeWidgetItem *root2 = new QTreeWidgetItem(treeWidget);
    root2->setText(0, "Linac");
    root2->setIcon(0, style->standardIcon(QStyle::SP_ComputerIcon));

    QTreeWidgetItem *root3 = new QTreeWidgetItem(treeWidget);
    root3->setText(0, "Storage Ring");
    root3->setIcon(0, style->standardIcon(QStyle::SP_ComputerIcon));

    // 为TMSR添加子节点
    QTreeWidgetItem *child1 = new QTreeWidgetItem(root1);
    child1->setText(0, "Vacuum System");
    child1->setIcon(0, style->standardIcon(QStyle::SP_DirIcon));

    QTreeWidgetItem *child2 = new QTreeWidgetItem(root2);
    child2->setText(0, "RF System");
    child2->setIcon(0, style->standardIcon(QStyle::SP_DirIcon));

    // 为Storage Ring添加子节点
    QTreeWidgetItem *child3 = new QTreeWidgetItem(root3);
    child3->setText(0, "Magnet System");
    child3->setIcon(0, style->standardIcon(QStyle::SP_DirIcon));

    // 为Vacuum System添加孙子节点
    QTreeWidgetItem *grandChild1 = new QTreeWidgetItem(child1);
    grandChild1->setText(0, "Pump 01");
    grandChild1->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    QTreeWidgetItem *grandChild2 = new QTreeWidgetItem(child1);
    grandChild2->setText(0, "Pressure Gauge");
    grandChild2->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    QTreeWidgetItem *grandChild3 = new QTreeWidgetItem(child2);
    grandChild3->setText(0, "Klystron");
    grandChild3->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    // 为Magnet System添加更多孙子节点
    QTreeWidgetItem *grandChild4 = new QTreeWidgetItem(child3);
    grandChild4->setText(0, "Dipole Magnet");
    grandChild4->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    QTreeWidgetItem *grandChild5 = new QTreeWidgetItem(child3);
    grandChild5->setText(0, "Quadrupole Magnet");
    grandChild5->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    QTreeWidgetItem *grandChild6 = new QTreeWidgetItem(child3);
    grandChild6->setText(0, "Sextupole Magnet");
    grandChild6->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    QTreeWidgetItem *grandChild7 = new QTreeWidgetItem(child3);
    grandChild7->setText(0, "Corrector Magnet");
    grandChild7->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    QTreeWidgetItem *grandChild8 = new QTreeWidgetItem(child3);
    grandChild8->setText(0, "Insertion Device");
    grandChild8->setIcon(0, style->standardIcon(QStyle::SP_FileIcon));

    // 展开所有节点
    treeWidget->expandAll();
}

void MainWindow::showContextMenu(const QPoint &pos)
{
    QTableWidget *activeTable = ui->active_alarm_table;
    QTableWidgetItem *item = activeTable->itemAt(pos);
    
    if (item) {
        // 显示右键菜单
        contextMenu->exec(activeTable->mapToGlobal(pos));
    }
}

void MainWindow::sendEmailForAlarm()
{
    qDebug() << "=== EMAIL SENDING FUNCTION START ===";
    
    try {
        QTableWidget *activeTable = ui->active_alarm_table;
        
        // 验证表格控件
        if (!activeTable) {
            qDebug() << "ERROR: active_alarm_table is null!";
            QMessageBox::warning(this, "错误", "报警表格控件无效");
            return;
        }
        
        int selectedRow = activeTable->currentRow();
        qDebug() << "Table validation:";
        qDebug() << "  Active table valid:" << (activeTable != nullptr);
        qDebug() << "  Selected row:" << selectedRow;
        qDebug() << "  Total rows:" << activeTable->rowCount();
        qDebug() << "  Total columns:" << activeTable->columnCount();
        
        if (selectedRow >= 0 && selectedRow < activeTable->rowCount()) {
            qDebug() << "=== EXTRACTING ALARM DATA ===";
            
            // 安全获取报警信息
            QString pvName, description, alarmSeverity, alarmMessage, alarmTime, alarmValue;
            
            try {
                pvName = activeTable->item(selectedRow, 0) ? activeTable->item(selectedRow, 0)->text() : "N/A";
                description = activeTable->item(selectedRow, 1) ? activeTable->item(selectedRow, 1)->text() : "N/A";
                alarmSeverity = activeTable->item(selectedRow, 4) ? activeTable->item(selectedRow, 4)->text() : "N/A";
                alarmMessage = activeTable->item(selectedRow, 5) ? activeTable->item(selectedRow, 5)->text() : "N/A";
                alarmTime = activeTable->item(selectedRow, 6) ? activeTable->item(selectedRow, 6)->text() : "N/A";
                alarmValue = activeTable->item(selectedRow, 7) ? activeTable->item(selectedRow, 7)->text() : "N/A";
                
                qDebug() << "Extracted alarm data:";
                qDebug() << "  PV Name:" << pvName;
                qDebug() << "  Description:" << description;
                qDebug() << "  Severity:" << alarmSeverity;
                qDebug() << "  Message:" << alarmMessage;
                qDebug() << "  Time:" << alarmTime;
                qDebug() << "  Value:" << alarmValue;
                
            } catch (const std::exception& e) {
                qDebug() << "EXCEPTION while extracting alarm data:" << e.what();
                QMessageBox::warning(this, "错误", "提取报警数据时发生错误");
                return;
            }
            
            // 构造邮件内容
            QString emailContent = QString(
                "报警通知\n\n"
                "PV名称: %1\n"
                "描述: %2\n"
                "严重程度: %3\n"
                "报警消息: %4\n"
                "报警时间: %5\n"
                "报警值: %6\n\n"
                "请及时处理此报警。"
            ).arg(pvName, description, alarmSeverity, alarmMessage, alarmTime, alarmValue);
            
            qDebug() << "Email content prepared, length:" << emailContent.length();
            
            qDebug() << "=== CREATING SMTP MAILER ===";
            
            // 创建SMTP邮件发送器
            SmtpMailer *mailer = new SmtpMailer(this);
            if (!mailer) {
                qDebug() << "ERROR: Failed to create SmtpMailer!";
                QMessageBox::critical(this, "错误", "无法创建邮件发送器");
                return;
            }
            
            qDebug() << "SmtpMailer created successfully:" << mailer;
            
            // 配置阿里云企业邮箱SMTP服务器
            qDebug() << "Configuring SMTP server...";
            mailer->setServerConfig("smtp.qiye.aliyun.com", 465, true);
            mailer->setCredentials("dorry@royosoft.cn", "lr4k4B2sNbwCmkuX");
            qDebug() << "SMTP server configured";
            
            qDebug() << "=== CREATING PROGRESS DIALOG ===";
            
            // 显示进度对话框
            QProgressDialog *progressDialog = new QProgressDialog("正在发送邮件...", "取消", 0, 0, this);
            if (!progressDialog) {
                qDebug() << "ERROR: Failed to create progress dialog!";
                if (mailer) {
                    mailer->deleteLater();
                }
                return;
            }
            
            progressDialog->setWindowModality(Qt::WindowModal);
            progressDialog->show();
            qDebug() << "Progress dialog created and shown:" << progressDialog;
            
            qDebug() << "=== CONNECTING SIGNALS ===";
            
            // 连接成功信号
            connect(mailer, &SmtpMailer::mailSent, this, [this, progressDialog, mailer]() {
                qDebug() << "=== MAIL SENT SIGNAL RECEIVED ===";
                qDebug() << "Scheduling UI update in main thread...";
                
                QTimer::singleShot(0, this, [this, progressDialog, mailer]() {
                    qDebug() << "=== PROCESSING MAIL SUCCESS IN MAIN THREAD ===";
                    
                    try {
                        if (progressDialog) {
                            qDebug() << "Closing progress dialog:" << progressDialog;
                            progressDialog->close();
                            progressDialog->deleteLater();
                            qDebug() << "Progress dialog closed and scheduled for deletion";
                        } else {
                            qDebug() << "WARNING: Progress dialog is null in success handler";
                        }
                        
                        qDebug() << "Showing success message box";
                        QMessageBox::information(this, "发送成功", "邮件发送成功！");
                        qDebug() << "Success message box shown";
                        
                        if (mailer) {
                            qDebug() << "Scheduling mailer for deletion:" << mailer;
                            mailer->deleteLater();
                            qDebug() << "Mailer scheduled for deletion";
                        } else {
                            qDebug() << "WARNING: Mailer is null in success handler";
                        }
                        
                        qDebug() << "=== MAIL SUCCESS PROCESSING COMPLETED ===";
                        
                    } catch (const std::exception& e) {
                        qDebug() << "EXCEPTION in mail success handler:" << e.what();
                    } catch (...) {
                        qDebug() << "UNKNOWN EXCEPTION in mail success handler";
                    }
                });
            });
            
            // 连接错误信号
            connect(mailer, &SmtpMailer::mailError, this, [this, progressDialog, mailer](const QString &error) {
                qDebug() << "=== MAIL ERROR SIGNAL RECEIVED ===";
                qDebug() << "Error message:" << error;
                qDebug() << "Scheduling error handling in main thread...";
                
                QTimer::singleShot(0, this, [this, progressDialog, mailer, error]() {
                    qDebug() << "=== PROCESSING MAIL ERROR IN MAIN THREAD ===";
                    
                    try {
                        if (progressDialog) {
                            qDebug() << "Closing progress dialog:" << progressDialog;
                            progressDialog->close();
                            progressDialog->deleteLater();
                            qDebug() << "Progress dialog closed and scheduled for deletion";
                        } else {
                            qDebug() << "WARNING: Progress dialog is null in error handler";
                        }
                        
                        qDebug() << "Showing error message box with error:" << error;
                        QMessageBox::warning(this, "发送失败", QString("邮件发送失败：%1").arg(error));
                        qDebug() << "Error message box shown";
                        
                        if (mailer) {
                            qDebug() << "Scheduling mailer for deletion:" << mailer;
                            mailer->deleteLater();
                            qDebug() << "Mailer scheduled for deletion";
                        } else {
                            qDebug() << "WARNING: Mailer is null in error handler";
                        }
                        
                        qDebug() << "=== MAIL ERROR PROCESSING COMPLETED ===";
                        
                    } catch (const std::exception& e) {
                        qDebug() << "EXCEPTION in mail error handler:" << e.what();
                    } catch (...) {
                        qDebug() << "UNKNOWN EXCEPTION in mail error handler";
                    }
                });
            });
            
            // 连接取消信号
            connect(progressDialog, &QProgressDialog::canceled, this, [mailer]() {
                qDebug() << "=== PROGRESS DIALOG CANCELED ===";
                if (mailer) {
                    qDebug() << "Scheduling mailer for deletion due to cancellation:" << mailer;
                    mailer->deleteLater();
                } else {
                    qDebug() << "WARNING: Mailer is null in cancel handler";
                }
            });
            
            qDebug() << "All signals connected successfully";
            
            qDebug() << "=== INITIATING MAIL SENDING ===";
            qDebug() << "About to call mailer->sendMail()";
            qDebug() << "Recipient: 6486073@qq.com";
            qDebug() << "Subject: 报警通知 -" << pvName;
            
            mailer->sendMail("6486073@qq.com", QString("报警通知 - %1").arg(pvName), emailContent);
            qDebug() << "mailer->sendMail() called successfully";
            
        } else {
            qDebug() << "=== NO VALID ROW SELECTED ===";
            qDebug() << "Selected row:" << selectedRow << "is invalid (total rows:" << activeTable->rowCount() << ")";
            QMessageBox::information(this, "提示", "请先选择要发送邮件的报警记录");
        }
        
    } catch (const std::exception& e) {
        qDebug() << "EXCEPTION in sendEmailForAlarm:" << e.what();
        QMessageBox::critical(this, "错误", QString("邮件发送过程中发生异常: %1").arg(e.what()));
    } catch (...) {
        qDebug() << "UNKNOWN EXCEPTION in sendEmailForAlarm";
        QMessageBox::critical(this, "错误", "邮件发送过程中发生未知异常");
    }
    
    qDebug() << "=== EMAIL SENDING FUNCTION END ===";
}

void MainWindow::initColorBlockFlashing()
{
    // 创建定时器用于颜色块闪烁
    flashTimer = new QTimer(this);
    connect(flashTimer, &QTimer::timeout, this, &MainWindow::flashColorBlock);
    flashTimer->start(1000); // 每秒闪烁一次

    // 初始化颜色状态
    isFlashing = false;

    // 存储报警盘界面各个系统标签的原始颜色
    originalColors.clear();
    originalColors["label_5"] = "background-color: rgb(250, 74, 74);";    // 保护系统 - 红色
    originalColors["label_6"] = "background-color: rgb(0, 254, 0);";      // 功率控制系统 - 绿色
    originalColors["label_7"] = "background-color: rgb(0, 254, 0);";      // 回路系统 - 绿色
    originalColors["label_8"] = "background-color: rgb(254, 0, 254);";    // 燃料盐装卸 - 紫色
    originalColors["label_10"] = "background-color: rgb(254, 0, 254);";   // 辅助工艺系统 - 紫色
    originalColors["label_11"] = "background-color: rgb(243, 181, 181);"; // 真空系统 - 浅红色
    originalColors["label_12"] = "background-color: rgb(254, 0, 254);";   // 换热系统 - 紫色
    originalColors["label_13"] = "background-color: rgb(252, 22, 22);";   // 电气系统 - 红色
    originalColors["label_14"] = "background-color: rgb(0, 254, 0);";     // 化学水处理系统 - 绿色
    originalColors["label_27"] = "background-color: rgb(239, 228, 228);"; // 气路系统 - 浅灰色
    originalColors["label_28"] = "background-color: rgb(0, 254, 0);";     // 发电系统 - 绿色
    originalColors["label_29"] = "background-color: rgb(254, 0, 254);";   // 冷却系统 - 紫色
}

void MainWindow::flashColorBlock()
{
    // 只在报警盘标签页激活时才执行闪烁
    if (ui->tabWidget->currentIndex() != 1) { // 报警盘是第2个标签页（索引为1）
        return;
    }

    if (!isFlashing) {
        // 设置闪烁颜色（白色）
        ui->label_5->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_6->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_7->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_8->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_10->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_11->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_12->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_13->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_14->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_27->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_28->setStyleSheet("background-color: rgb(255, 255, 255);");
        ui->label_29->setStyleSheet("background-color: rgb(255, 255, 255);");
        isFlashing = true;
    } else {
        // 恢复原始颜色
        ui->label_5->setStyleSheet(originalColors["label_5"]);
        ui->label_6->setStyleSheet(originalColors["label_6"]);
        ui->label_7->setStyleSheet(originalColors["label_7"]);
        ui->label_8->setStyleSheet(originalColors["label_8"]);
        ui->label_10->setStyleSheet(originalColors["label_10"]);
        ui->label_11->setStyleSheet(originalColors["label_11"]);
        ui->label_12->setStyleSheet(originalColors["label_12"]);
        ui->label_13->setStyleSheet(originalColors["label_13"]);
        ui->label_14->setStyleSheet(originalColors["label_14"]);
        ui->label_27->setStyleSheet(originalColors["label_27"]);
        ui->label_28->setStyleSheet(originalColors["label_28"]);
        ui->label_29->setStyleSheet(originalColors["label_29"]);
        isFlashing = false;
    }
}

void MainWindow::showTabContextMenu(const QPoint &pos)
{
    // 获取右键点击的Tab索引
    rightClickedTabIndex = ui->tabWidget->tabBar()->tabAt(pos);
    
    if (rightClickedTabIndex >= 0) {
        // 显示右键菜单
        tabContextMenu->exec(ui->tabWidget->tabBar()->mapToGlobal(pos));
    }
}

void MainWindow::openTabInNewWindow()
{
    if (rightClickedTabIndex < 0 || rightClickedTabIndex >= ui->tabWidget->count()) {
        return;
    }
    
    // 获取Tab的标题和内容
    QString tabTitle = ui->tabWidget->tabText(rightClickedTabIndex);
    QWidget *tabContent = ui->tabWidget->widget(rightClickedTabIndex);
    
    if (!tabContent) {
        return;
    }
    
    // 创建新窗口
    QMainWindow *newWindow = new QMainWindow();
    newWindow->setWindowTitle(tabTitle);
    newWindow->resize(800, 600);
    
    // 创建新的TabWidget来包含所有tab标签
    QTabWidget *newTabWidget = new QTabWidget(newWindow);
    newWindow->setCentralWidget(newTabWidget);
    
    // 复制所有tab到新窗口
    for (int i = 0; i < ui->tabWidget->count(); ++i) {
        QString title = ui->tabWidget->tabText(i);
        
        if (i == rightClickedTabIndex) {
            // 对于被右键点击的tab，移动原始widget到新窗口
            QWidget *originalWidget = ui->tabWidget->widget(i);
            
            // 创建一个克隆的widget来替代原始widget
            QWidget *clonedWidget = new QWidget();
            
            // 这里应该根据具体的widget类型来进行深度复制
            // 为了简化，我们创建一个基本的布局
            QVBoxLayout *layout = new QVBoxLayout(clonedWidget);
            
            // 根据tab的类型来创建相应的内容
            if (title.contains("Tree")) {
                QTreeWidget *newTree = new QTreeWidget();
                // 复制原始树的内容...
                layout->addWidget(newTree);
            } else if (title.contains("Table") || title.contains("Alarm")) {
                QTableWidget *newTable = new QTableWidget();
                // 复制原始表格的内容...
                layout->addWidget(newTable);
            } else {
                // 其他类型的widget
                QLabel *placeholder = new QLabel("内容已在新窗口中打开");
                placeholder->setAlignment(Qt::AlignCenter);
                layout->addWidget(placeholder);
            }
            
            newTabWidget->addTab(clonedWidget, title);
        } else {
            // 对于其他tab，创建占位符
            QWidget *placeholderWidget = new QWidget();
            QVBoxLayout *placeholderLayout = new QVBoxLayout(placeholderWidget);
            QLabel *placeholderLabel = new QLabel("此标签页内容在主窗口中");
            placeholderLabel->setAlignment(Qt::AlignCenter);
            placeholderLayout->addWidget(placeholderLabel);
            
            newTabWidget->addTab(placeholderWidget, title);
        }
    }
    
    // 设置新窗口的当前tab为被右键点击的tab
    newTabWidget->setCurrentIndex(rightClickedTabIndex);
    
    // 设置新窗口的样式
    newWindow->setStyleSheet(
        "QTabWidget::pane {"
        "    border: 1px solid #C0C0C0;"
        "    top: -1px;"
        "}"
        "QTabBar::tab {"
        "    background: #E0E0E0;"
        "    border: 1px solid #C0C0C0;"
        "    padding: 5px 10px;"
        "    margin-right: 2px;"
        "}"
        "QTabBar::tab:selected {"
        "    background: #FFFFFF;"
        "    border-bottom: 1px solid #FFFFFF;"
        "}"
    );
    
    // 显示新窗口
    newWindow->show();
}




